package com.gzsxy.esjy.sign.configuration;

import com.alibaba.fastjson.JSON;


import com.gzsxy.esjy.sign.cache.SignCacheManager;
import com.gzsxy.esjy.sign.dto.BaseSignProtocolDto;

import com.gzsxy.esjy.sign.dto.SignTaskDto;
import com.gzsxy.esjy.sign.service.GSSignBusinessService;
import com.gzsxy.esjy.sign.service.GSSignService;
import com.gzsxy.esjy.sign.service.impl.DefaultBusinessHandlerServiceImpl;
import com.gzsxy.esjy.sign.util.SignProtocolUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Map;

/**
 * @author zhangxiaolong
 * @since 2022/7/15
 */
@Slf4j
@EnableScheduling
@ComponentScan(basePackages = "com.gzsxy.esjy")
public class SignAutoConfiguration {

    @Autowired
    private SignCacheManager cacheManager;

    @Autowired
    private GSSignBusinessService gsSignBusinessService;

    @Autowired
    private GSSignService gsSignService;


    @Value("${server.port}")
    private int serverPort;

    /**
     * 初始化启动器
     *
     * @return
     */
    @Bean(name = "bootstrap")
    public Bootstrap bootstrap() {
        // 相当于线程池
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        return bootstrap;
    }

    @Bean
    @ConditionalOnMissingBean(GSSignBusinessService.class)
    public GSSignBusinessService businessHandlerService(SignCacheManager signCacheManager) {
        return new DefaultBusinessHandlerServiceImpl(signCacheManager, serverPort);
    }

    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkSignTask() {
        Map<String, SignTaskDto> signTaskCache = cacheManager.getSignTaskCache();
        signTaskCache.forEach((k, v) -> {
            long millis = System.currentTimeMillis();
            long signTimeOut = gsSignBusinessService.getSignTimeOut();
            if (millis - v.getRequestTime().getTime() > signTimeOut) {
                log.info("处理超时任务：{}", JSON.toJSONString(v));
                BaseSignProtocolDto screenCancelSign = SignProtocolUtil.getCancelSignByType(v.getRequestId(), v.getDevType(), gsSignBusinessService.getSignOkUrl());
                gsSignService.cancelSign(v.getIp(), v.getPort(), screenCancelSign);
            }
        });
    }

}

